package operations;

import books.Book;
import books.BookList;
import sun.font.FontRunIterator;

import java.util.Scanner;

public class DelOperation implements IOperation{
    @Override
    public void work(BookList bookList){
        System.out.println("删除图书");
        System.out.println("请输入要删除的图书名");

        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        int currentSize = bookList.getUsedSize();
        int index = -1;//是否存在该图书的标志

        // 遍历bookList查找是否存在要删除的图书
        for (int i = 0; i < currentSize; i++) {
            Book book = bookList.getPos(i);
            if(name.equals(book.getName())){
                index = i;  // 找到该书就改变index的值，退出循环
                break;
            }
        }

        // 此时判断是否进行删除操作
        if(index == -1){
            System.out.println("要删除的图书不存在");
        }else{
            // 执行删除操作，讲此时index后的所有元素前移1位即可
            for (int i = index; i < currentSize-1; i++) {
                //把i+1下标的书放到i下标
                Book book = bookList.getPos(i+1);
                bookList.setBooks(book,i);
            }
            //每次删除后进行置空
            bookList.setBooks(null,currentSize-1);
            bookList.setUsedSize(currentSize-1);
            System.out.println(name+"已被删除");
        }
    }

}
